import Vue from 'vue';
import Router from 'vue-router';
import store from '@/store';

Vue.use(Router);

// 修复重复导航报错
const originalPush = Router.prototype.push;
Router.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => {
    if (err.name !== 'NavigationDuplicated') throw err;
  });
};

// 公共路由
export const constantRoutes = [
  {
    path: '/login',
    component: () => import('@/views/Login'),
    meta: { title: '登录' }
  },
  {
    path: '/404',
    component: () => import('@/views/404'),
    meta: { title: '404' }
  },
  {
    path: '/home',
    component: () => import('@/components/Layout'),
    redirect: '/home/index',
    children: [
      {
        path: 'index',
        component: () => import('@/views/Home.vue'),
        name: 'Home',
        meta: { title: '首页', icon: 'dashboard', affix: true }
      },
      {
        path: 'password',
        name: 'Password',
        component: () => import('@/views/Password.vue'),
        meta: { title: '修改密码' }
      }
    ]
  },
  {
    path: '/',
    component: () => import('@/views/public/Layout.vue'),
    redirect: '/index',
    children: [
      {
        path: 'index',
        name: 'PublicIndex',
        component: () => import('@/views/public/Index.vue'),
        meta: { title: '公共首页' }
      },
      {
        path: 'help',
        name: 'Help',
        component: () => import('@/views/public/help.vue'),
        meta: { title: '帮助中心' }
      }
    ]
  }
];

const router = new Router({
  mode: 'history',
  scrollBehavior: () => ({ y: 0 }),
  routes: constantRoutes
});

// 路由守卫
router.beforeEach(async (to, from, next) => {
  // 获取token
  const token = store.state.auth.token || JSON.parse(localStorage.getItem('token'));

  // 处理根路径重定向
  if (to.path === '/') {
    next('/index');
    return;
  }

  // 已登录用户访问登录页，重定向到首页
  if (token && to.path === '/login') {
    next('/home');
    return;
  }

  // 定义公共路由
  const publicPages = ['/index', '/help', '/login'];
  const isPublicPage = publicPages.includes(to.path);

  // 处理公共页面访问
  if (isPublicPage) {
    next();
    return;
  }

  // 处理需要认证的页面
  if (token) {
    // 检查路由是否已加载
    const hasRoutes = store.state.auth.routes?.length > 0;
    if (hasRoutes) {
      next();
      return;
    }

    try {
      // 加载动态路由
      const accessRoutes = await store.dispatch('auth/reloadRoutes');
      if (accessRoutes.length > 0) {
        next({ ...to, replace: true });
      } else {
        await store.dispatch('auth/logout');
        next('/index');
      }
    } catch (error) {
      console.error('Error loading routes:', error);
      await store.dispatch('auth/logout');
      next('/index');
    }
  } else {
    // 未登录用户访问需要认证的页面，重定向到公共首页
    next('/index');
  }
});

export default router;
